package com.tongshu.naive.chat.infrastructure.common;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SocketChannelUtil {
    // 用户
    // userId Channel
    private static Map<String, Channel> userChannel = new ConcurrentHashMap<>();
    // channelId UserId
    private static Map<String, String> userChannelId = new ConcurrentHashMap<>();
    // 群组
    // talkId channelGroup
    private static Map<String, ChannelGroup> channelGroupMap = new ConcurrentHashMap<>();

    public static void addChannel(String userId, Channel channel) {
        userChannel.put(userId, channel);
        userChannelId.put(channel.id().toString(), userId);
    }

    public static void removeChannel(String channelId) {
        String userId = userChannelId.get(channelId);
        if (null == userId) return;
        userChannel.remove(userId);
    }

    public static void removeUserChannelByUserId(String userId) {
        userChannel.remove(userId);
    }

    public static Channel getChannel(String userId) {
        return userChannel.get(userId);
    }

    /**
     * 添加群组成员通信管道
     * @param talkId            对话框ID[群号]
     * @param userChannel       群员通信管道
     */
    public synchronized static void addChannelGroup(String talkId, Channel userChannel) {
        ChannelGroup channelGroup = channelGroupMap.get(talkId);
        if (null == channelGroup) {
            channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            channelGroupMap.put(talkId, channelGroup);
        }
        channelGroup.add(userChannel);
    }

    /**
     * 根据对话框ID删除某群组中某用户通信管道
     * @param talkId
     * @param userChannel
     */
    public synchronized static void removeChannelGroup(String talkId, Channel userChannel) {
        ChannelGroup channelGroup = channelGroupMap.get(talkId);
        if (null == channelGroup) return;
        channelGroup.remove(userChannel);
    }

    /**
     * 删除所有群组中该用户通信管道
     * @param channel
     */
    public static void removeChannelGroupByChannel(Channel channel) {
        for (ChannelGroup channelGroup : channelGroupMap.values()) {
            channelGroup.remove(channel);
        }
    }

    /**
     * 根据对话框ID获取群组的通信管道
     * @param talkId
     * @return
     */
    public static ChannelGroup getChannelGroup(String talkId) {
        return channelGroupMap.get(talkId);
    }
}
